/*
 * Copyright 2019-2025 the original author or authors.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * https://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.iiifi.kite.cloud.feign;

import java.lang.reflect.Method;
import java.util.Objects;

import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import org.springframework.lang.Nullable;

import com.fasterxml.jackson.databind.JsonNode;
import com.iiifi.kite.core.result.Result;
import com.iiifi.kite.core.result.SystemCode;
import com.iiifi.kite.core.util.JsonUtils;
import com.iiifi.kite.core.util.ObjectUtils;
import com.iiifi.kite.core.util.StringPool;

import feign.FeignException;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * fallBack 代理处理
 *
 * @author kite@iiifi.com 花朝
 */
@Slf4j
@AllArgsConstructor
public class KiteFeignFallback<T> implements MethodInterceptor {
    private final Class<T> targetType;
    private final String targetName;
    private final Throwable cause;

    @Nullable
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        String errorMessage = cause.getMessage();
        log.error("KiteFeignFallback:[{}.{}] serviceId:[{}] message:[{}]", targetType.getName(), method.getName(),
                targetName, errorMessage);
        Class<?> returnType = method.getReturnType();
        // 暂时不支持 flux，rx，异步等，返回值不是 R，直接返回 null。
        if (Result.class != returnType) {
            return null;
        }
        // 非 FeignException，直接返回 【100009】请求被拒绝
        if (!(cause instanceof FeignException)) {
            return Result.fail(SystemCode.REQ_REJECT, errorMessage);
        }
        FeignException exception = (FeignException) cause;
        String content = exception.contentUTF8();
        // 如果返回的数据为空
        if (ObjectUtils.isEmpty(content)) {
            return Result.fail(SystemCode.REQ_REJECT, errorMessage);
        }
        // 转换成 jsonNode 读取，因为直接转换，可能 对方放回的并 不是 R 的格式。
        JsonNode resultNode = JsonUtils.readTree(content);
        // 判断是否 Result 格式 返回体
        if (resultNode.has(StringPool.CODE)) {
            return JsonUtils.getInstance().convertValue(resultNode, Result.class);
        }
        return Result.fail(SystemCode.FAILURE, resultNode.toString());
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        KiteFeignFallback<?> that = (KiteFeignFallback<?>) o;
        return targetType.equals(that.targetType);
    }

    @Override
    public int hashCode() {
        return Objects.hash(targetType);
    }
}
